﻿using DoNetDrive.Protocol.Door.Door8800.SystemParameter.TCPSetting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DoNetDrive.Protocol.Door.Test.TCPPublisher
{
    /// <summary>
    /// TCP信息发布者
    /// </summary>
    public class TCPDetailIObservable : IObservable<TCPDetail>
    {
        /// <summary>
        /// 订阅者列表
        /// </summary>
        private readonly List<IObserver<TCPDetail>> observers;
        public TCPDetailIObservable()
        {
            observers = new List<IObserver<TCPDetail>>();
        }
        /// <summary>
        /// 订阅信息
        /// </summary>
        /// <param name="observer"></param>
        /// <returns></returns>
        public IDisposable Subscribe(IObserver<TCPDetail> observer)
        {
            if (!observers.Contains(observer))
            {
                observers.Add(observer);
            }
            return new UnSubscribe(observers, observer);
        }
        /// <summary>
        /// 发布信息
        /// </summary>
        /// <param name="data"></param>
        public void Publish(TCPDetail data)
        {
            foreach (var observer in observers)
            {
                observer.OnNext(data);
            }
        }

        /// <summary>
        /// 取消订阅
        /// </summary>
        private class UnSubscribe : IDisposable
        {
            private readonly List<IObserver<TCPDetail>> observers;
            private readonly IObserver<TCPDetail> observer;
            public UnSubscribe(List<IObserver<TCPDetail>> observers, IObserver<TCPDetail> observer)
            {
                this.observer = observer;
                this.observers = observers;
            }
            public void Dispose()
            {
                if (observers != null && observer != null)
                {
                    observers.Remove(observer);
                }
            }
        }
    }
}
